import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import HistoryView from '../views/HistoryView.vue'
import UploadView from "@/views/UploadView.vue"
import LoginView from "@/views/LoginView.vue" // 确保引入正确的组件

const routes = [
    {
        path: '/',
        name: 'Home',
        component: HomeView,
        meta: { requiresAuth: true }
    },
    {
        path: '/history',
        name: 'History',
        component: HistoryView,
        meta: { requiresAuth: true }
    },
    {
        path: '/upload',
        name: 'Upload',
        component: UploadView,
        meta: { requiresAuth: true }
    },
    {
        path: '/login',
        name: 'Login',
        component: LoginView,
        meta: { guestOnly: true }
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'

    // 已登录用户访问需要认证的页面
    if (to.meta.requiresAuth && !isLoggedIn) {
        next('/login')
    }
    // 已登录用户访问登录页
    else if (to.meta.guestOnly && isLoggedIn) {
        next('/')
    }
    else {
        next()
    }
})

export default router
